<template>
  <el-card shadow="navar">
    <el-row :gutter="15">
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="120px"
      >
        <el-col :span="24">
          <el-form-item label="优惠券名称" prop="couponName">
            <el-input
              v-model.trim="formData.couponName"
              placeholder="请输入优惠券名称"
              clearable
              maxlength="16"
              show-word-limit
              :style="{ width: 'calc(50% - 67px)' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="优惠券类别" prop="category">
            <el-select
              v-model.number="formData.category"
              placeholder="请选择优惠券类别"
              clearable
              @change="categoryChange"
              :style="{ width: 'calc(50% - 67px)' }"
            >
              <el-option
                v-for="item in dict.type.coupon_type"
                :key="item.value"
                :label="item.label"
                :value="parseInt(item.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="优惠金额" prop="money">
            <el-input
              v-model.trim="formData.money"
              placeholder="请输入优惠金额"
              clearable
              :style="{ width: 'calc(50% - 67px)' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="消费金额" prop="conditionMoney">
            <el-input
              v-model.trim="formData.conditionMoney"
              placeholder="请输入消费金额"
              clearable
              :style="{ width: 'calc(50% - 67px)' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否允许转赠" prop="isTurn">
            <el-radio-group v-model="formData.isTurn">
              <el-radio
                v-for="item in dict.type.coupon_is_turn"
                :key="item.value"
                :label="parseInt(item.value)"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发放开始时间" prop="sendTimeStart">
            <el-date-picker
              v-model.trim="formData.sendTimeStart"
              type="datetime"
              placeholder="请选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptionsStart"
              :style="{ width: '100%' }"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发放结束时间" prop="sendTimeEnd">
            <el-date-picker
              v-model.trim="formData.sendTimeEnd"
              type="datetime"
              placeholder="请选择开始时间"
              :style="{ width: '100%' }"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptionsEnd"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="termTime">
            <span slot="label" :class="{ red: formData.useTimeType == '2' }"
              >使用有效期</span
            >
            <el-radio
              v-model="formData.useTimeType"
              @change="useTimeTypeChange"
              :label="1"
              :style="{ width: '50%' }"
            >
              <el-date-picker
                v-model="formData.termTime"
                @change="sendTime"
                type="datetimerange"
                range-separator="至"
                value-format="yyyy-MM-dd HH:mm:ss"
                :disabled="formData.useTimeType == '2'"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="useTime">
            <el-radio
              v-model="formData.useTimeType"
              :label="2"
              @change="useTimeTypeChange"
              :style="{ width: '50%' }"
            >
              领券后有效天数
              <el-input
                v-model.number="formData.useTime"
                placeholder="0代表长期有效"
                :disabled="formData.useTimeType == '1'"
                maxlength="6"
                clearable
                :style="{ width: 'calc(100% - 212px)', marginLeft: '15px' }"
              >
              </el-input>
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用说明" prop="useNotice">
            <el-input
              v-model.trim="formData.useNotice"
              type="textarea"
              placeholder="请输入使用说明"
              maxlength="200"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 4 }"
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitForm" v-onceClick
              >提交</el-button
            >
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </el-card>
</template>

<script>
import { addCoupon, putCoupon, getCouponById } from '@/api/coupon/manage.js'
export default {
  components: {},
  dicts: ['coupon_type', 'coupon_is_turn', 'coupon_use_time_type'],
  data() {
    // 验证开始时间的规则
    var checkTimeStart = (rule, value, callback) => {
      if (
        this.formData.sendTimeEnd != '' &&
        value > this.formData.sendTimeEnd
      ) {
        callback(new Error('活动开始时间需小于活动结束时间'))
      }
      this.$refs['elForm'].clearValidate('sendTimeEnd')
      return callback()
    }
    // 验证结束时间的规则
    var checkTimeEnd = (rule, value, callback) => {
      if (
        this.formData.sendTimeStart != '' &&
        value < this.formData.sendTimeStart
      ) {
        callback(new Error('活动结束时间需大于活动开始时间'))
      }
      this.$refs['elForm'].clearValidate('sendTimeStart')
      return callback()
    }
    return {
      // 开始结束日期限制
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.formData.sendTimeEnd) {
            return (
              time.getTime() >= new Date(this.formData.sendTimeEnd).getTime()
            )
          }
        },
      },
      // 结束日期限制
      pickerOptionsEnd: {
        disabledDate: (time) => {
          if (this.formData.sendTimeStart) {
            return (
              time.getTime() <= new Date(this.formData.sendTimeStart).getTime()
            )
          }
        },
      },
      formData: {
        couponName: '',
        category: '',
        money: '',
        conditionMoney: '',
        isTurn: 0,
        sendTimeStart: '',
        sendTimeEnd: '',
        useTimeType: 1,
        termTime: [],
        useTimeStart: null,
        useTimeEnd: null,
        useNotice: '',
        useTime: null,
      },
      rules: {
        couponName: [
          {
            required: true,
            message: '请输入优惠券名称',
            trigger: 'blur',
          },
        ],
        category: [
          {
            required: true,
            message: '请选择优惠券类别',
            trigger: 'change',
          },
        ],
        money: [
          {
            required: true,
            message: '请输入优惠金额',
            trigger: 'blur',
          },
          {
            pattern: /^[0-9]+(.[0-9]{1,2})?$/,
            message: '优惠金额保留两位小数',
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (
                parseFloat(value) > parseFloat(this.formData.conditionMoney)
              ) {
                callback(new Error('优惠金额不能大于消费金额'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
        conditionMoney: [
          {
            required: true,
            message: '请输入消费金额',
            trigger: 'blur',
          },
          {
            pattern: /^[0-9]+(.[0-9]{1,2})?$/,
            message: '消费金额保留两位小数',
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (parseFloat(value) < parseFloat(this.formData.money)) {
                callback(new Error('消费金额不能小于优惠金额'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
        isTurn: [
          {
            required: true,
            message: '请选择是否允许转赠',
            trigger: 'change',
          },
        ],
        sendTimeStart: [
          {
            required: true,
            message: '请输入活动开始时间',
            trigger: 'change',
          },
          { validator: checkTimeStart, trigger: 'change' },
        ],
        sendTimeEnd: [
          {
            required: true,
            message: '请输入活动结束时间',
            trigger: 'change',
          },
          { validator: checkTimeEnd, trigger: 'change' },
        ],
        useTimeType: [
          {
            required: true,
            message: '请选择',
            trigger: 'change',
          },
        ],
        termTime: [
          {
            required: true,
            message: '请选择时间',
            trigger: 'change',
          },
        ],
        useTime: [
          {
            required: false,
            message: '请输入有效期',
            trigger: 'blur',
          },
          {
            pattern: /^([0]|[1-9][0-9]*)$/,
            message: '只能输入零或正整数',
            trigger: 'blur',
          },
        ],
        useNotice: [
          {
            required: true,
            message: '请输入活动说明',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  mounted() {
    if (this.$route.params.id) {
      this.getCouponById()
    }
  },
  methods: {
    getCouponById() {
      getCouponById({ id: this.$route.params.id }).then((res) => {
        this.formData = res.data
        if (res.data.useTimeType == 1) {
          this.$set(this.formData, 'termTime', [
            res.data.useTimeStart,
            res.data.useTimeEnd,
          ])
        } else {
          this.$set(this.formData, 'termTime', ['', ''])
        }
        this.$forceUpdate()
        this.useTimeTypeChange(res.data.useTimeType)
      })
    },
    // 时间转换
    sendTime(val) {
      this.formData.useTimeStart = val ? val[0] : ''
      this.formData.useTimeEnd = val ? val[1] : ''
    },
    // 验证使用有效期
    useTimeTypeChange(val) {
      if (val == '2') {
        this.$set(this.formData, 'termTime', ['', ''])
        this.rules.termTime[0].required = false
        this.rules.useTime[0].required = true
        this.$refs['elForm'].validateField('termTime')
      } else {
        this.$set(this.formData, 'useTime', null)
        this.rules.useTime[0].required = false
        this.rules.termTime[0].required = true
        this.$refs['elForm'].validateField('useTime')
      }
    },
    // 验证
    categoryChange(val) {
      //优惠金额
      if (val == '1' || val == '3') {
        this.rules.money[0].required = true
      } else {
        this.rules.money[0].required = false
      }
      //使用条件
      if (val == '1' || val == '2') {
        this.rules.conditionMoney[0].required = true
      } else {
        this.rules.conditionMoney[0].required = false
      }
      //使用条件值处理
      if (val == '2') {
        this.formData.conditionMoney = 0
      } else {
        this.formData.conditionMoney = null
      }
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) {
          this.$message.error('验证不通过，请检查输入')
          return
        } else {
          if (this.$route.params.id) {
            putCoupon(
              Object.assign(this.formData, { couponId: this.$route.params.id })
            ).then((res) => {
              if (res.code == 200) {
                this.goBack()
              }
              this.$message.success(res.msg)
            })
          } else {
            addCoupon(this.formData).then((res) => {
              if (res.code == 200) {
                this.goBack()
              }
              this.$message.success(res.msg)
            })
          }
        }
        // TODO 提交表单
      })
    },
    goBack() {
      this.$router.go(-1) // 返回
      //关闭子页面
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex(
          (item) => item.path === this.$route.path
        ),
        1
      )
      this.$router.push(
        this.$store.state.tagsView.visitedViews[
          this.$store.state.tagsView.visitedViews.length - 1
        ].path
      )
    },
  },
}
</script>
<style scoped>
.red::before {
  content: '*';
  color: #ff4949;
  margin-right: 4px;
}
</style>

